﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MKAdminCore.DTO.Web.Common;
using MKAdminCore.DTO.Web.Login;
using MKAdminCore.DTO.Web.Organization.PermissionSetting;
using MKAdminCore.IService.Web.Organization;
using MKAdminCore.ServiceImpl.Web.Common;
using MKAdminCore.ToolKit;
using Dapper;

namespace MKAdminCore.ServiceImpl.Web.Organization
{
    public class PermissionSettingService : IPermissionSettingService
    {
        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public PagingList<GetPermissionListModel> List(GetPermissionListParameter parameter, UserInfo userInfo)
        {
            PagingList<GetPermissionListModel> list = new PagingList<GetPermissionListModel>();

            return list;
        }

        /// <summary>
        /// 分配权限弹窗列表
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public PagingList<GetPermissionListModel> AllotList(GetPermissionAllotListParameter parameter, UserInfo userInfo)
        {
            PagingList<GetPermissionListModel> list = new PagingList<GetPermissionListModel>();

            //using (var util = new DBHelper())
            //{
            //    int superiorId = 0;
            //    string sqlSuperior = $"Select ParentId From dbo.Tb_mt_AgentUser With(NoLock) Where Id = {parameter.updatorAgentId}";
            //    object obj = util.ExecuteScalar(sqlSuperior);
            //    superiorId = Convert.ToInt32(obj);

            //    if (superiorId > 0)
            //    {
            //        StringBuilder sql = new StringBuilder();
            //        sql.AppendLine($@"
            //                      SELECT RoleId,RoleName,Creator,CONVERT(varchar(20),[CreateTime],120) As CreateTime
            //                        FROM DBO.Agent_Role_Info With(NoLock)
            //                      Where StatusCode = 1 And CreatorAgentId = {superiorId}");

            //        string sqlPaging = SqlPagingHelper.GetPagingSql(sql.ToString(), parameter.pageIndex, parameter.pageSize, "Order By CreateTime Desc");
            //        list = util.GetDataTable(sqlPaging).ConvertToPagingList<GetPermissionListModel>();
            //    }
            //}

            return list;
        }

        /// <summary>
        /// 获取权限功能信息表
        /// </summary>
        /// <returns></returns>
        public Result<List<PermissionDTO>> GetPermissionInfo()
        {
            var result = new Result<List<PermissionDTO>>()
            {
                status = true,
                data = new List<PermissionDTO>()
            };
            var allMenuList = GetRightInfo();
            //所有主菜单信息   
            var mainMenuListInfo = allMenuList.Where(x => x.RightParentId == -1).OrderBy(x => x.OrderNo).ToList(); //这个根 5个根节点
            if (mainMenuListInfo.Count > 0)
            {
                /*  var list = new List<PermissionDTO>();*/
                foreach (var mainMenu in mainMenuListInfo)
                {
                    var menu = new PermissionDTO
                    {
                        PermissionId = mainMenu.RightId.ToString(),
                        PermissionName = mainMenu.RightName,
                        FPermissionId = mainMenu.RightParentId.ToString(),

                    };
                    result.data.Add(menu);//主菜单
                    MakeSonMenu(mainMenu.RightId, allMenuList, result.data);//tag标记二级菜单  状态为收缩
                }
            }
            return result;
        }
        private List<PermissionDTO> MakeSonMenu(int rightId, List<RightInfo> menuList, List<PermissionDTO> result)
        {
            if (menuList == null)
                return null;

            var sonMenu = menuList.Where(x => x.RightParentId == rightId).OrderBy(x => x.OrderNo).ToList();
            if (sonMenu.Count > 0)
            {

                foreach (var son in sonMenu)
                {
                    PermissionDTO menu;

                    menu = new PermissionDTO
                    {
                        PermissionId = son.RightId.ToString(),
                        PermissionName = son.RightName,
                        FPermissionId = son.RightParentId.ToString(),
                    };
                    result.Add(menu);

                    MakeSonMenu(son.RightId, menuList, result);
                }

                return result;
            }
            return null;
        }
        private List<RightInfo> GetRightInfo()
        {
            List<RightInfo> info = new List<RightInfo>();
            //StringBuilder str = new StringBuilder();
            //using (var db = new DBHelper())
            //{
            //    str.AppendLine("Select * from Agent_Right_Info with(nolock) Where StatusCode=0");
            //    var dt = db.GetDataTable(str.ToString());
            //    info = dt.ToList<RightInfo>();
            //}
            return info;
        }

        /// <summary>
        /// 权限新增
        /// </summary>
        /// <returns></returns>
        public Result AddRole(RoleAddParameter parameter, UserInfo info)
        {
            var result = new Result()
            {
                status = true,
                msg = "操作成功"
            };
            if (string.IsNullOrEmpty(parameter.RightName) || parameter.RightName == "")
            {
                result.status = false;
                result.msg = "请输入权限名称";
                return result;
            }
            if (parameter.RightIdsList == null || parameter.RightIdsList.Count <= 0)
            {
                result.status = false;
                result.msg = "请至少选择一个权限节点";
                return result;
            }
            parameter.RightIdsList.Distinct();
            int res = InsertRole(parameter, info);
            if (res <= 0)
            {
                result.status = false;
                result.msg = "操作失败";
            }
            return result;
        }

        private int InsertRole(RoleAddParameter parameter, UserInfo info)
        {
            int result = 0;

            //using (var db = new DBHelper())
            //{
            //    try
            //    {
            //        db.BeginTransaction();//事务开始
            //        //1、插入 Agent_Role_Info 
            //        StringBuilder str = new StringBuilder();
            //        str.AppendLine("Insert Into [dbo].[Agent_Role_Info] (RoleName,RoleDescri,StatusCode,Updator,UpdateTime,Creator,CreateTime,Remark,AgentName,CreatorAgentId)");
            //        str.AppendLine("Values(@RoleName,'',1,@Updator,getdate(),@Creator,getdate(),@Remark,@AgentName,@CreatorAgentId)");
            //        str.AppendLine("Select SCOPE_IDENTITY()");
            //        List<SqlParameter> param = new List<SqlParameter>();
            //        param.Add(new SqlParameter() { ParameterName = "@RoleName", DbType = DbType.String, Value = parameter.RightName });
            //        param.Add(new SqlParameter() { ParameterName = "@Updator", DbType = DbType.String, Value = info.OperatorName });
            //        param.Add(new SqlParameter() { ParameterName = "@Creator", DbType = DbType.String, Value = info.OperatorName });
            //        param.Add(new SqlParameter() { ParameterName = "@Remark", DbType = DbType.String, Value = string.IsNullOrEmpty(parameter.Remark) ? "" : parameter.Remark.Trim() });
            //        param.Add(new SqlParameter() { ParameterName = "@AgentName", DbType = DbType.String, Value = info.OperatorNo });
            //        param.Add(new SqlParameter() { ParameterName = "@CreatorAgentId", DbType = DbType.String, Value = info.OperatorId });

            //        int roleId = Convert.ToInt32(db.ExecuteScalar(str.ToString(), CommandType.Text, param.ToArray()));
            //        //2、插入 Agent_Role_Right_Config

            //        foreach (var item in parameter.RightIdsList)
            //        {
            //            StringBuilder roleConfig = new StringBuilder();
            //            roleConfig.AppendLine($"Insert Into  [dbo].Agent_Role_Right_Config (RoleId,RightId) Values({roleId},{item})");
            //            db.ExecuteQuery(roleConfig.ToString());
            //        }

            //        db.CommitTransaction();
            //        result = 1;
            //    }
            //    catch (Exception ex)
            //    {
            //        LogHelper.Error("新增权限失败=>" + ex);
            //        db.RollbackTransaction();
            //    }
            //}

            return result;
        }
        /// <summary>
        /// 权限编辑
        /// </summary>
        /// <returns></returns>
        public Result EditRole(RoleEditSaveParameter parameter, UserInfo info)
        {
            var result = new Result()
            {
                status = true
            };
            if (parameter.RoleId == 0)
            {
                result.status = false;
                result.msg = "权限Id不能为空";
                return result;
            }
            if (parameter.RightIdList == null || parameter.RightIdList.Count <= 0)
            {
                result.status = false;
                result.msg = "权限节点不能为空";
                return result;
            }
            parameter.RightIdList.Distinct();
            int res = UpdateRole(parameter, info);
            if (res <= 0)
            {
                result.status = false;
                result.msg = "操作失败";
            }
            return result;
        }
        private int UpdateRole(RoleEditSaveParameter parameter, UserInfo info)
        {
            int result = 0;

            //using (var db = new DBHelper())
            //{
            //    try
            //    {
            //        db.BeginTransaction();//事务开始
            //        // 一、更新 Agent_Role_Info 
            //        // (1）、更新 
            //        StringBuilder str = new StringBuilder();
            //        str.AppendLine($"Update  [dbo].[Agent_Role_Info] Set RoleName=@RoleName,Remark=@Remark,UpdateTime=getdate(),Updator=@Updator Where RoleId={parameter.RoleId}");
            //        List<SqlParameter> param = new List<SqlParameter>();
            //        param.Add(new SqlParameter() { ParameterName = "@RoleName", DbType = DbType.String, Value = parameter.RoleName });
            //        param.Add(new SqlParameter() { ParameterName = "@Updator", DbType = DbType.String, Value = info.OperatorName });
            //        param.Add(new SqlParameter() { ParameterName = "@Remark", DbType = DbType.String, Value = string.IsNullOrEmpty(parameter.Remark) ? "" : parameter.Remark.Trim() });
            //        db.ExecuteQuery(str.ToString(), CommandType.Text, param.ToArray());
            //        //二、先删除在插入配置表
            //        //（1）、删除
            //        StringBuilder strDel = new StringBuilder();
            //        strDel.AppendLine($"Delete From Agent_Role_Right_Config Where RoleId={parameter.RoleId}");
            //        db.ExecuteQuery(strDel.ToString());
            //        //（2）、插入 Agent_Role_Right_Config

            //        foreach (var item in parameter.RightIdList)
            //        {
            //            StringBuilder roleConfig = new StringBuilder();
            //            roleConfig.AppendLine($"Insert Into  [dbo].Agent_Role_Right_Config (RoleId,RightId) Values({parameter.RoleId},{item})");
            //            db.ExecuteQuery(roleConfig.ToString());
            //        }

            //        db.CommitTransaction();
            //        result = 1;
            //    }
            //    catch (Exception ex)
            //    {
            //        LogHelper.Error("编辑权限失败=>" + ex);
            //        db.RollbackTransaction();
            //    }
            //}

            return result;
        }

        /// <summary>
        /// 权限删除
        /// </summary>
        /// <returns></returns>
        public Result DeleteRole(RoleDelParameter parameter, UserInfo info)
        {
            var result = new Result()
            {
                status = true
            };
            if (parameter.RoleId == 0)
            {
                result.status = false;
                result.msg = "权限Id不能为空";
                return result;
            }
            //using (var db = new DBHelper())
            //{
            //    StringBuilder str = new StringBuilder();
            //    str.AppendLine($"Update  [dbo].[Agent_Role_Info] Set StatusCode=3,UpdateTime=getdate(),Updator=@Updator Where RoleId={parameter.RoleId}");
            //    List<SqlParameter> param = new List<SqlParameter>();
            //    param.Add(new SqlParameter() { ParameterName = "@Updator", DbType = DbType.String, Value = info.OperatorName });
            //    if (db.ExecuteQuery(str.ToString(), CommandType.Text, param.ToArray()) <= 0)
            //    {
            //        result.status = false;
            //        result.msg = "操作失败";
            //    }
            //    else
            //    {
            //        result.msg = "操作成功";
            //    }
            //}
            return result;
        }


        /// <summary>
        /// 根据Id获取自身权限
        /// </summary>
        /// <param name="agentId"></param>
        /// <returns></returns>
        public List<RightInfo> GetPermissionInfoById(int agentId)
        {
            List<RightInfo> info = new List<RightInfo>();
            //StringBuilder sql = new StringBuilder();
            //sql.AppendLine("Select Distinct ORI.RightId,ORI.RightParentId,ORI.TypeCode,ORI.OrderNo,");
            //sql.AppendLine("   ORI.RightName,ORI.IconName,ORI.ResourceName,ORI.MenuPageUrl,ORI.Remark ");
            //sql.AppendLine("From dbo.Agent_Role_Config ORC");
            //sql.AppendLine("Inner Join dbo.Tb_mt_AgentUser   OI ON ORC.AgentId = OI.Id");
            //sql.AppendLine("Inner Join dbo.Agent_Role_Right_Config ORRC ON ORC.RoleId = ORRC.RoleId");
            //sql.AppendLine("Inner Join dbo.Agent_Right_Info ORI ON ORRC.RightId = ORI.RightId and ORI.StatusCode=0");
            //sql.AppendLine("Where ORC.AgentId = @AgentId And OI.AccountStatusCode = 0");

            //List<SqlParameter> param = new List<SqlParameter>();
            //param.Add(new SqlParameter() { ParameterName = "@AgentId", DbType = DbType.String, Value = agentId });
            //using (var db = new DBHelper())
            //{
            //    var dt = db.GetDataTable(sql.ToString(), CommandType.Text, param.ToArray());
            //    info = dt.ToList<RightInfo>();
            //}
            return info;
        }
        /// <summary>
        /// 根据权限ID获取角色权限
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public Result<GetRoleRightModel> GetRoleRightByRoleId(RoleEditParameter parameter)
        {
            var result = new Result<GetRoleRightModel>()
            {
                status = true,
                data = new GetRoleRightModel()
            };
            //if (parameter.RoleId == 0)
            //{
            //    result.status = false;
            //    result.msg = "权限Id不能为空";
            //    return result;
            //}
            //StringBuilder strSql = new StringBuilder();
            //strSql.AppendLine("select ORRC.RightId from [dbo].[Agent_Role_Right_Config] ORRC");
            //strSql.AppendLine("INNER JOIN Agent_Right_Info ORI ON ORI.RightId=ORRC.RightId");
            //strSql.AppendLine("where ORRC.RoleId=@RoleId");
            //strSql.AppendLine("Select RoleName,Remark From Agent_Role_Info with(nolock) where RoleId=@RoleId  ");
            //List<SqlParameter> param = new List<SqlParameter>();
            //param.Add(new SqlParameter() { ParameterName = "@RoleId", DbType = DbType.Int32, Value = parameter.RoleId });
            //using (var db = new DBHelper())
            //{
            //    var ds = db.GetDataSet(strSql.ToString(), CommandType.Text, param.ToArray());
            //    var dtEmumerable = from dt in ds.Tables[0].AsEnumerable() select dt;

            //    //权限 代码
            //    result.data.RightIdList = dtEmumerable.Select(q => q.Field<int>("RightId")).ToList();

            //    result.data.Remark = ds.Tables[1].Rows[0]["Remark"].ToString();
            //    result.data.RoleName = ds.Tables[1].Rows[0]["RoleName"].ToString();
            //}
            return result;
        }

        /// <summary>
        /// 获取用户菜单权限信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public Result<GetPermissionDataListModel> PermissionMenuList(UserInfo userInfo)
        {
            var list = new Result<GetPermissionDataListModel>()
            {
                data = new GetPermissionDataListModel()
            };
            list.data.menuData = GetUserMenuPermissionList(userInfo).data;

            return list;
        }

        /// <summary>
        /// 获取用户功能权限信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<HttpResponseResult> PermissionFunctionList(int rightId, UserInfo userInfo)
        {
            var list = new HttpResponseResult<GetPermissionDataListModel>()
            {
                Data = new GetPermissionDataListModel()
            };
            list.Data.functionData = await GetUserFunctionPermissionList(rightId, userInfo);

            return list;
        }

        /// <summary>
        /// 获取用户菜单权限信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="rightType">0:菜单权限 1:功能权限</param>
        /// <returns></returns>
        private Result<List<PermissionMenuDataModel>> GetUserMenuPermissionList(UserInfo userInfo)
        {
            var list = new Result<List<PermissionMenuDataModel>>()
            {
                data = new List<PermissionMenuDataModel>()
            };
            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                var sql = "";
                //管理员 测试账号 默认所有权限
                if (userInfo.OperatorId == 1 || userInfo.OperatorNo == "test")
                {
                    sql = $@"SELECT RightId rightId,RightParentId rightParentId
	                                ,RightName rightName,IconName iconName
	                                ,ResourceName resourceName,MenuPageUrl menuPageUrl
                                FROM DBO.OperatorRightInfo ori With(NoLock)
                                     WHERE ori.TypeCode = 0
	                                 And ori.StatusCode = 0
                                ORDER BY ori.OrderNo ASC";
                }
                else
                {
                    sql = $@"SELECT ari.RightId rightId,ari.RightParentId rightParentId
	                                ,ari.RightName rightName,ari.IconName iconName
	                                ,ari.ResourceName resourceName,ari.MenuPageUrl menuPageUrl 
                                FROM DBO.OperatorRightInfo ari WITH(NOLOCK)
                                LEFT JOIN DBO.OperatorRoleRightConfig arrc WITH(NOLOCK) ON ari.RightId = arrc.RightId
                                LEFT JOIN DBO.OperatorRoleInfo arli WITH(NOLOCK) ON arli.RoleId = arrc.RoleId
                                LEFT JOIN DBO.OperatorRoleConfig arc WITH(NOLOCK) ON arrc.RoleId = arc.RoleId
                                LEFT JOIN DBO.OperatorInfo tmau With(NoLock) On tmau.OperatorId = arc.OperatorId
                                WHERE tmau.OperatorId = {userInfo.OperatorId}
                                    AND ari.TypeCode = 0
                                    AND ari.StatusCode = 0
                                    AND tmau.StatusCode = 0
                                    AND arli.StatusCode = 0
                                ORDER BY ari.OrderNo ASC";
                }

                list.data = conn.Query<PermissionMenuDataModel>(sql).ToList();
                //list.data = util.GetDataTable(sql).ToList<PermissionMenuDataModel>();
            }

            return list;
        }

        /// <summary>
        /// 获取用户功能权限信息
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="rightType">0:菜单权限 1:功能权限</param>
        /// <returns></returns>
        private async Task<List<int>> GetUserFunctionPermissionList(int rightId, UserInfo userInfo)
        {
            var list = new List<UserFunctionPermissionInfo>();
            using (var conn = new SqlConnection(AppSettingsJsonInfo.ConnectionStrings.ReadConnStr))
            {
                var sql = "";
                if (userInfo.OperatorId == 1 || userInfo.OperatorId == 10 || userInfo.OperatorId == 10000)
                {
                    sql = $@"SELECT ari.RightId RightId,ari.RightName
                                FROM DBO.OperatorRightInfo ari With(NoLock)
                                     WHERE ari.TypeCode = 1
                                  And ari.StatusCode = 0
                                    AND ari.RightParentId = {rightId}
                                ORDER BY ari.OrderNo ASC";
                }
                else
                {
                    sql = $@"SELECT ari.RightId RightId,ari.RightName
                                FROM DBO.OperatorRightInfo ari WITH(NOLOCK)
                                LEFT JOIN DBO.OperatorRoleRightConfig arrc WITH(NOLOCK) ON ari.RightId = arrc.RightId
                                LEFT JOIN DBO.OperatorRoleInfo arli WITH(NOLOCK) ON arli.RoleId = arrc.RoleId
                                LEFT JOIN DBO.OperatorRoleConfig arc WITH(NOLOCK) ON arrc.RoleId = arc.RoleId
                                LEFT JOIN DBO.OperatorInfo tmau With(NoLock) On tmau.OperatorId = arc.OperatorId
                                WHERE tmau.OperatorId = {userInfo.OperatorId}
                                AND ari.TypeCode = 1
                                AND tmau.StatusCode = 0
                                AND ari.RightParentId = {rightId}
                                AND arli.StatusCode = 0";
                }

                var permissionQuery = await conn.QueryAsync<UserFunctionPermissionInfo>(sql);
                return permissionQuery.Select(q => q.RightId).ToList();
            }
        }

        /// <summary>
        /// 验证当前用户是否拥有该资源名称权限
        /// </summary>
        /// <param name="resourceName"></param>
        /// <returns></returns>
        public Result<bool> UserPermissionVerify(string resourceName, UserInfo userInfo)
        {
            var result = new Result<bool>();
            try
            {
                if (userInfo.OperatorId == 1 || userInfo.OperatorId == 10 || userInfo.OperatorId == 10000)
                {
                    result.data = true;
                }
                else
                {
                    //using (var util = new DBHelper())
                    //{
                    //    var sql = $@"SELECT RightId rightId,RightParentId rightParentId
                    //             ,RightName rightName,IconName iconName
                    //             ,ResourceName resourceName,MenuPageUrl menuPageUrl 
                    //                FROM DBO.Agent_Right_Info 
                    //                    WHERE StatusCode = 0 AND TypeCode = 1 
                    //                    And ResourceName = @ResourceName";

                    //    List<SqlParameter> param = new List<SqlParameter>();
                    //    param.Add(new SqlParameter() { ParameterName = "@ResourceName", DbType = DbType.String, Value = resourceName });

                    //    var rightInfo = util.GetDataTable(sql, CommandType.Text, param.ToArray()).ToList<PermissionMenuDataModel>();

                    //    if (rightInfo.Any())
                    //    {
                    //        //查询用户本身是否有该资源权限
                    //        var userSql = $@"SELECT ari.RightId rightId,ari.RightParentId rightParentId
                    //                         ,ari.RightName rightName,ari.IconName iconName
                    //                         ,ari.ResourceName resourceName,ari.MenuPageUrl menuPageUrl 
                    //                            FROM DBO.Agent_Right_Info ari WITH(NOLOCK)
                    //                            LEFT JOIN DBO.Agent_Role_Right_Config arrc WITH(NOLOCK) ON ari.RightId = arrc.RightId
                    //                            LEFT JOIN DBO.Agent_Role_Info arli WITH(NOLOCK) ON arli.RoleId = arrc.RoleId
                    //                            LEFT JOIN DBO.Agent_Role_Config arc WITH(NOLOCK) ON arrc.RoleId = arc.RoleId
                    //                            LEFT JOIN DBO.Tb_mt_AgentUser tmau With(NoLock) On tmau.Id = arc.AgentId
                    //                            WHERE tmau.Id = {userInfo.OperatorId}
                    //                            AND ari.TypeCode = 1
                    //                            AND tmau.AccountStatusCode = 0
                    //                            AND ari.StatusCode = 0
                    //                            AND arli.StatusCode = 1
                    //                            AND ari.ResourceName = @ResourceName";

                    //        List<SqlParameter> paramR = new List<SqlParameter>();
                    //        paramR.Add(new SqlParameter() { ParameterName = "@ResourceName", DbType = DbType.String, Value = resourceName });

                    //        var userRightInfo = util.GetDataTable(userSql, CommandType.Text, paramR.ToArray()).ToList<PermissionMenuDataModel>();

                    //        if (userRightInfo.Any())
                    //        {
                    //            //有权限
                    //            result.data = true;
                    //        }
                    //        else
                    //        {
                    //            result.data = false;
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //没有配置相关权限，则默认设置有权限
                    //        result.data = true;
                    //    }
                    //}
                }
            }
            catch (Exception ex)
            {
                result.status = false;
                result.data = false;
                result.msg = "获取用户资源权限异常";
                //LogHelper.Error("获取用户资源权限异常", ex);
            }

            return result;
        }


    }
}
